package com.software.task.controller;

import com.alibaba.excel.EasyExcel;
import com.software.task.anno.Debounce;
import com.software.task.pojo.PageBean;
import com.software.task.pojo.Result;
import com.software.task.pojo.Subject;
import com.software.task.service.SubjectService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 浦慧慧
 * @since 2024/12/15 11.34
 * @version 1.0
 */
@RestController
@RequestMapping("/subjects")
public class SubjectController {

    @Resource
    private SubjectService subjectService;
    /**
     * 登录接口 登录成功返回token，登录失败返回错误信息
     * @return token
     */
    @Debounce()
    @PostMapping
    public Result<?> add(@RequestBody @Validated(Subject.Add.class) Subject subject) {
        subjectService.add(subject);
        return Result.success();
    }
   /**
    * 列表接口
    * @param pageNum 页码
    * @param pageSize 页大小
    * @param categoryId 分类ID
    * @param state 状态   0：未完成   1：已完成
    * @return 列表
    */
    @Debounce()
    @GetMapping
    public Result<PageBean<Subject>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false)String state
    ){
        PageBean<Subject> pageBean = subjectService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pageBean);
    }

    @Debounce()
    @PutMapping
    public Result<?> update(@RequestBody @Validated(Subject.Update.class) Subject subject) {
        subjectService.update(subject);
        return Result.success();
    }

    @Debounce()
    @DeleteMapping
    public Result<?> delete(@RequestParam Integer id) {
        subjectService.delete(id);
        return Result.success();
    }

    /**
     * 导出
     *
     * @param response 响应对象
     * @param subject 查询对象
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, Subject subject) throws
            IOException {
    // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("作业信息", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    // 查询列表数据
        List<Subject> list = subjectService.getList(subject);
    // 导出数据
        EasyExcel.write(response.getOutputStream(), Subject.class).sheet("作业详情").doWrite(list);
    }

    /**
     * 导入模版下载
     *
     * @param response 响应对象
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
    // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
    // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("作业信息导入模版", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" +
                fileName + ".xlsx");
    // 导出模版
        EasyExcel.write(response.getOutputStream(), Subject.class).sheet("用户信息导入模版").doWrite(new ArrayList<>());
    }

    /**
     * 导入
     *
     * @param file 上传的文件
     * @return 导入结果
     */
    @PostMapping("/importExcel")
    public Result<?> importExcel(@RequestPart(value = "file") MultipartFile file) {
        try {
    // 读取excel数据
            List<Subject> subjectlist = EasyExcel.read(file.getInputStream())
                    .head(Subject.class)
                    .sheet()
                    .doReadSync();
            subjectlist.stream()
                    .peek(subject -> {
                        subject.setCreateTime(LocalDateTime.now());
                        subject.setUpdateTime(LocalDateTime.now());
                    })
                    .toList();
            int result = subjectService.batchSave(subjectlist);
            if (result > 0) {
                return Result.success("导入成功！");
            }
            return Result.error("导入失败！");
        } catch (IOException e) {
            return Result.error("导入失败！");
        }
    }
}




